<?

class FormNewTask extends CFormModel{
    
    public $projectID;
    public $text;
    public $critical;
    public $files;
    
    public function rules(){
        return array(
            array('projectID, text', 'required'),
            array('projectID', 'numerical', 'integerOnly'=>true),
            array('critical', 'boolean'),
        );
    }
    
    public function attributeLabels(){
        return array(
            'text'=>TaskModule::t('fields', 'Текст'),
            'critical'=>TaskModule::t('fields', 'Важная задача'),
            'files'=>TaskModule::t('fields', 'Прикрепить файл'),
        );
    }
    
    public function createTask(){
        
        $lastTask = Task::GetLastInProject($this->projectID);
        $sort = $lastTask ? $lastTask->sort+1 : 0;
        
        $TASK = new Task;
        $TASK->project_id = $this->projectID;
        $TASK->status = Task::model()->rstatuses[TaskModule::t('fields', 'Новая')];
        $TASK->critical = $this->critical;
        $TASK->sort = $sort;
        $TASK->text = $this->text;
        
        $TASK->archived = 0;
        $TASK->time_create = time();
        $TASK->user_id = Yii::app()->user->id;
        
        if($TASK->validate()){
            
            $TASK->save();
            
            if(!empty($this->files)){
                foreach($this->files['name']['files'] as $k=>$v){
                    $ar = array(
                        'name' => $this->files['name']['files'][$k],
                        'type' => $this->files['type']['files'][$k],
                        'tmp_name' => $this->files['tmp_name']['files'][$k],
                        'error' => $this->files['error']['files'][$k],
                        'size' => $this->files['size']['files'][$k],
                    );
                    $F = File::model()->push($ar);
                    $FL = new TaskFile;
                    $FL->task_id = $TASK->id;
                    $FL->file_id = $F->id;
                    $FL->save();
                }
            }
            
            return true;
            
        }
        
        return $TASK->getErrors();
        
    }
    
}
